<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Token;
use app\common\model\Member;
use app\common\model\Merchant;
use app\common\model\Merchantuser;
use app\common\model\Mycard;
use app\common\model\Order;
use app\common\model\Reconciliation;
use app\common\model\Regionserviceuser;
use app\common\model\Merchant as MerchantModel;
use app\common\model\Washlog;
use Exception;
use fast\Random;
use think\Db;
use think\Validate;

/**
 * 区域服务商接口
 */
class Regionservice extends Api
{
    protected $noNeedLogin = ['merchantLogin', 'merchantRego', 'cardType'];
    protected $noNeedRight = ['*'];
    protected $regionserviceUser = [];
    protected $regionservice = [];

    public function _initialize()
    {
        parent::_initialize();
        if (!$this->auth->match($this->noNeedLogin)) {
            /*判断当前账号身份 start*/
            $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
            $token = Token::get($token);
            if ($token["type"] != 2) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
            /*判断当前账号身份 end*/
            $user = Regionserviceuser::get($this->auth->id);
            $regionservice = \app\common\model\Regionservice::find($user["regionservice_id"]);
            if (empty($regionservice)) $this->error("区域服务商不存在");
            if (empty($regionservice["status"])) $this->error("区域服务商审核中");
            if ($regionservice["status"] == 2) $this->error("区域服务商已被驳回：" . $regionservice["remark"]);
            if ($regionservice["status"] == 3) $this->error("区域服务商已被禁用");
            $this->regionserviceUser = $user;
            $this->regionservice = $regionservice;
        }
    }

    /**
     * 区域服务商修改资料
     * */
    public function regionserviceUpdate()
    {
        $data = [
            ['name', 'require', '服务商名称不能为空'],
            ['region', 'require', '签约区域不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $regionservice = \app\common\model\Regionservice::get($this->regionserviceUser["regionservice_id"]);
        if (empty($regionservice)) $this->error("服务商不存在");
        $region=explode(",",$params["region"]);
        foreach ($region as $v){
            $address_rules= \app\common\model\Regionservice::where('FIND_IN_SET("'.$v.'", region)')
                ->where("id <> ".$this->regionservice["id"])->where(["status"=>'1'])->find();
            if(!empty($address_rules)) $this->error($v."已存在规则");
        }
        $ret = false;
        Db::startTrans();
        try {
            $ret = $regionservice->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success(__('修改成功'));
        } else {
            $this->error("修改失败");
        }
    }

    /******************************** 员工管理 start*****************************************************************************/
    /**
     * 员工列表
     * */
    public function listUser()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list = Regionserviceuser::field("id,name,avatar,mobile,status")
            ->where(["regionservice_id" => $this->regionserviceUser["regionservice_id"], "is_super" => '0'])
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功", $list);
    }

    /**
     * 新增员工
     * */
    public function addUser()
    {
        $data = [
            ['name', 'require', '员工姓名不能为空'],
            ['avatar', 'require', '员工照片不能为空'],
            ['mobile', 'require|regex:/^1\d{10}$/|unique:regionserviceuser', '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
            ['password', 'require|regex:\S{6,30}', '密码不能为空|密码长度必须在6-30位之间，不能包含空格'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $model = new Regionserviceuser();
        $params["regionservice_id"] = $this->regionserviceUser["regionservice_id"];
        $params['salt'] = Random::alnum();
        $params['password'] = md5(md5($params['password']) . $params['salt']);
        $model->allowField(true)->save($params);
        $this->success("成功");
    }

    /**
     * 修改员工
     * */
    public function updateUser()
    {
        $data = [
            ['id', 'require', 'id不能为空不能为空'],
            ['avatar', 'require', '员工照片不能为空'],
            ['mobile', 'require|regex:/^1\d{10}$/|unique:regionserviceuser,mobile,' . $this->request->param("id"), '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        if ($params['password']) {
            if (!Validate::is($params['password'], '\S{6,30}')) {
                $this->error("密码格式错误");
            }
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($params['password']) . $params['salt']);
        } else {
            unset($params['password'], $params['salt']);
        }
        $model = new Regionserviceuser();
        $user = $model->get($params["id"]);
        if (empty($user)) $this->error("员工不存在");
        $user->allowField(true)->save($params);
        $this->success("成功");
    }

    /**
     * 删除员工
     * */
    public function delUser()
    {
        if (!$this->request->param("id")) $this->error("id为空");
        $list = Regionserviceuser::field("id")->find($this->request->param("id"));
        if (empty($list)) $this->error("员工不存在");
        $list->delete();
        $this->success("成功");
    }

    /**
     * 查看员工详情
     * */
    public function seeUser()
    {
        if (!$this->request->param("id")) $this->error("id为空");
        $list = Regionserviceuser::field("id,name,avatar,mobile,status,createtime")->find($this->request->param("id"));
        if (empty($list)) $this->error("员工不存在");
        $this->success("成功", $list);
    }

    /**
     * 修改员工状态
     * */
    public function statusUser()
    {
        if (!$this->request->param("id")) $this->error("id为空");
        if (!in_array($this->request->param("status"), [1, 2])) $this->error("状态错误");
        $list = Regionserviceuser::field("id,name,avatar,mobile,status,createtime")->find($this->request->param("id"));
        if (empty($list)) $this->error("员工不存在");
        $list->save(["status" => $this->request->param("status")]);
        $this->success("成功", $list);

    }
    /******************************** 员工管理 end*****************************************************************************/


    /**
     * 店铺记录表
     * */
    public function merchantList()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $address = explode(",", $this->regionservice["region"]);
        if (!empty($address)) {
            $where = "address like '" . $address[0] . "%'";
            foreach ($address as $k => $v) {
                if ($k > 0) {
                    $where .= " or address like '" . $v . "%'";
                }
            }
        }
        $list = MerchantModel::field("id,name,address,status,is_trila,openswitch,mobile,telephone")
            //->whereLike("name","%". $this->request->param("name")."%")
            ->where(["status" => '1'])
            ->where($where)
            ->order("createtime", "desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功", $list);
    }

    /**
     * 店铺统计
     * */
    public function merchantCensus()
    {
        /*$where='FIND_IN_SET("'.$this->regionserviceUser["region"].'", (CONCAT(SUBSTRING_INDEX(classify,"-",1),
            SUBSTRING_INDEX(SUBSTRING_INDEX(classify,"-",-2),"-",1),
            SUBSTRING_INDEX(SUBSTRING_INDEX(classify,"-",-3),"-",-1))
            ))';*/
        $address = explode(",", $this->regionservice["region"]);
        if (!empty($address)) {
            $where = "address like '" . $address[0] . "%'";
            foreach ($address as $k => $v) {
                if ($k > 0) {
                    $where .= " or address like '" . $v . "%'";
                }
            }
        }
        $today = MerchantModel::field("count(id) value")
            ->whereTime("createtime", "today")
            ->where(["status" => '1'])
            ->where($where)->buildSql();//今日新增店铺
        $normal = MerchantModel::field("count(id) value")
            ->where(["status" => '1', "openswitch" => "1"])
            ->where($where)->buildSql();//正常营业
        $abnormal = MerchantModel::field("count(id) value")
            ->where(["status" => '1', "openswitch" => "0"])
            ->where($where)->buildSql();//异常营业
        $list = MerchantModel::field("count(id) value")
            ->where(["status" => '1'])
            ->where($where)
            ->union([$today, $normal, $abnormal], true)
            ->select();//所有
        $data["all"] = $list[0]["value"];
        $data["today"] = $list[1]["value"];
        $data["normal"] = $list[2]["value"];
        $data["abnormal"] = $list[3]["value"];
        $this->success("成功", $data);
    }

    /**
     * 获取推广码
     * */
    public function getPromotionCode()
    {
        $this->regionserviceUser = \app\common\model\Regionserviceuser::get(9);
        $code = [
            "promotion_code" => $this->regionserviceUser["promotion_code"],
            "promotion_url" => $this->regionserviceUser["promotion_url"],
        ];
        if (empty($this->regionserviceUser["promotion_code"])) {
            $mycardModel = new MerchantModel();
            $code = $mycardModel->getPromotionCode($this->auth->id, 3);//生成二维码
        }
        $this->success("成功", $code);
    }

    /**
     *核销订单列表
     * */
    public function writeOrder()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list = Washlog::field("id,type_data,mycard_id,card_type_name,merchant_name,regionservice_commission,price,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime")
            ->where(["regionservice_id" => $this->regionserviceUser["regionservice_id"]])
            ->where("type_data <> '2'");
        $all_money = Washlog::field("id,type_data,mycard_id,card_type_name,merchant_name,regionservice_commission,price,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime")
            ->where(["regionservice_id" => $this->regionserviceUser["regionservice_id"]])
            ->where("type_data <> '2'");
        if ($this->request->param("day")) {
            $day = $this->request->param("day");
            $day_field = "today";
            if ($day == 2) $day_field = "month";
            if($day==3) $day_field="year";
            $list = $list->whereTime("createtime", $day_field);
            $all_money = $all_money->whereTime("createtime", $day_field);
        } else {
            if ($this->request->param("start_time")) {
                $list = $list->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
                $all_money = $all_money->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
            }
        }
        $all_money= $all_money->sum("regionservice_commission");
        $list = $list->order("createtime", "desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])->toArray();
        $list["all_money"] = $all_money;
        $this->success("成功", $list);
    }
    /**
     * 分销订单
     * */
    public function allList(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $order=Order::field("order_no id,0 type_data,name card_type_name,'' merchant_name,regionservice_commission,merchant_id,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime")
            ->where(["regionservice_id"=>$this->regionserviceUser["regionservice_id"]])->whereIn("status",['1','3'])
            ->whereIn("type_data", ['0', '2']);
        $list=Washlog::field("id,type_data,card_type_name,merchant_name,regionservice_commission,merchant_id,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime")
            ->where(["regionservice_id"=>$this->regionserviceUser["regionservice_id"]])
            ->where("type_data <> '2'");
        $order_money=Order::field("sum(regionservice_commission) all_money")
            ->where(["regionservice_id"=>$this->regionserviceUser["regionservice_id"]])->whereIn("status",['1','3'])
            ->whereIn("type_data", ['0', '2']);
        $list_money=Washlog::field("sum(regionservice_commission) all_money")
            ->where(["regionservice_id"=>$this->regionserviceUser["regionservice_id"]])
            ->where("type_data <> '2'");
        if($this->request->param("day")){
            $day=$this->request->param("day");
            $day_field="today";
            if($day==2) $day_field="month";
            if($day==3) $day_field="year";
            $list=$list->whereTime("createtime",$day_field);
            $order=$order->whereTime("createtime",$day_field);
            $order_money=$order_money->whereTime("createtime",$day_field);
            $list_money=$list_money->whereTime("createtime",$day_field);
        }else{
            if($this->request->param("start_time")){
                $list=$list->whereTime('createtime', 'between', [strtotime($this->request->param("start_time")."00:00:00"),strtotime($this->request->param("end_time")."23:59:59")]);
                $order=$order->whereTime('createtime', 'between', [strtotime($this->request->param("start_time")."00:00:00"),strtotime($this->request->param("end_time")."23:59:59")]);
                $list_money=$list_money->whereTime('createtime', 'between', [strtotime($this->request->param("start_time")."00:00:00"),strtotime($this->request->param("end_time")."23:59:59")]);
                $order_money=$order_money->whereTime('createtime', 'between', [strtotime($this->request->param("start_time")."00:00:00"),strtotime($this->request->param("end_time")."23:59:59")]);
            }
        }
        $order_money=$order_money->buildSql();
        $all_money=$list_money->union([$order_money],true)->select();
        $order=$order->buildSql();
        $list=$list->union([$order],true)->buildSql();
        $list = Db::table($list.' as f')
            ->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v){
                /*if($v["type"]==2){
                    $mycard_name=Mycard::field("name")->where(["id"=>$v["mycard_id"]])->find();
                    $v["mycard_name"]=$mycard_name["name"];
                    unset($v["mycard_id"]);
                }*/
                if(empty($v["type_data"])){
                    $merchant=Merchant::field("name")->where(["id"=>$v["merchant_id"]])->find();
                    $v["merchant_name"]=$merchant["name"]??'';
                }
                return $v;
            })
            ->toArray();
        $list["all_money"]=$all_money[0]["all_money"]+$all_money[1]["all_money"].'';
        $this->success("成功", $list);
    }

    /**
     * 商品订单
     * */
    public function goodsList()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $order = Order::field("order_no id,0 type_data,0 mycard_id,name card_type_name,'' merchant_name,merchant_id,regionservice_commission,price,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime")
            ->where(["regionservice_id" => $this->regionserviceUser["regionservice_id"]])
            ->whereIn("status",['1','3'])
            ->whereIn("type_data", ['0', '2']);
        $list = Washlog::field("id,type_data,mycard_id,card_type_name,merchant_name,merchant_id,regionservice_commission,price,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime")
            ->where(["regionservice_id" => $this->regionserviceUser["regionservice_id"], "type_data" => '2']);
        $all_money_sql = Washlog::where(["regionservice_id" => $this->regionserviceUser["regionservice_id"], "type_data" => '2']);
        $all_money_sql2 = Order::where(["regionservice_id" => $this->regionserviceUser["regionservice_id"]])
            ->whereIn("status",['1','3'])
            ->whereIn("type_data", ['0', '2']);
        if ($this->request->param("day")) {
            $day = $this->request->param("day");
            $day_field = "today";
            if ($day == 2) $day_field = "month";
            if($day==3) $day_field="year";
            $list = $list->whereTime("createtime", $day_field);
            $all_money_sql2 = $all_money_sql2->whereTime("createtime", $day_field);
            $all_money_sql = $all_money_sql->whereTime("createtime", $day_field);
            $order = $order->whereTime("createtime", $day_field);
        } else {
            if ($this->request->param("start_time")) {
                $list = $list->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
                $all_money_sql2 = $all_money_sql2->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
                $all_money_sql = $all_money_sql->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
                $order = $order->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
            }
        }
        $order = $order->buildSql();
        $list = $list->union([$order], true)->buildSql();
        $all_money= $all_money_sql->sum("regionservice_commission");
        $all_money2= $all_money_sql2->sum("regionservice_commission");
        $list = Db::table($list . ' as f')
            ->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v){
                if ($v["type_data"] == 2) {
                    $mycard_name = Mycard::field("name")->where(["id" => $v["mycard_id"]])->find();
                    $v["mycard_name"] = $mycard_name["name"]??'';
                }
                if (empty($v["type_data"])) {
                    $merchant = MerchantModel::field("name")->where(["id" => $v["merchant_id"]])->find();
                    $v["merchant_name"] = $merchant["name"]??'';
                }
                unset($v["mycard_id"]);
                return $v;
            })
            ->toArray();
        $list["all_money"] = $all_money+$all_money2.'';
        $this->success("成功", $list);
    }

    /**
     * 生成对账单
     * */
    public function reconciliation()
    {
        //$this->auth->id = 7;
        $model=new Reconciliation();
        $order = Order::field("id,name,'' card_type_name,createtime,'' merchant_name,merchant_id,'' member_nickname,member_id,regionservice_commission,regionservice_status,0 type_data")
            ->where(["regionservice_id" => $this->regionserviceUser["regionservice_id"], "regionservice_status" => '0'])
            ->whereIn("status", ['1', '3'])
            ->whereIn("type_data", ['0', '2']);
        $list = Washlog::field("id,name,card_type_name,createtime,merchant_name,merchant_id,member_nickname,member_id,regionservice_commission,regionservice_status,type_data")
            ->where(["regionservice_id" => $this->regionserviceUser["regionservice_id"], "regionservice_status" => '0'])
            ->where("type_data <> '2'");
        if ($this->request->param("start_time") && !empty($this->request->param("start_time"))) {
            $list = $list->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
            $order = $order->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
        }
        $order = $order->buildSql();
        $list = $list->union($order, true)->select();
        if (empty($list)) $this->error("没有可生成对账单");
        foreach ($list as &$v) {
            if ($v["type_data"] == 0) {
                $merchant = MerchantModel::field("name")->where(["id" => $v["merchant_id"]])->find();
                $v["merchant_name"] = $merchant["name"] ?? '';
            }
            $member = \app\common\model\Member::field("nickname")->where(["id" => $v["member_id"]])->find();
            $v["member_nickname"] = $member["nickname"] ?? '';
            $model=new Member();
            $v["member_nickname"]=$model->emoji_decode($v["member_nickname"]);
            $v["regionservice_status"] = $v["regionservice_status"] == 0 ? "未分佣" : "已分佣";
            $v["type_data"] = $v["type_data"] == 0 ? "商品" : ($v["type_data"] == 1 ? "卡包" : ($v["type_data"] == 2 ? "店铺洗车卡" : "实体卡"));
        }
        $url = $this->export_data($list, $this->request->param("start_time"),$this->request->param("end_time"),$this->regionserviceUser["regionservice_id"]);
        $model->allowField(true)->save([
            "regionservice_id"=>$this->auth->id,
            "start_time"=>$this->request->param("start_time"),
            "end_time"=>$this->request->param("end_time"),
            "url"=>$url,
        ]);//对账单记录
        $this->success("成功", $url);
    }

    public function export_data($dataArr, $start_time = 0,$end_time=0,$regionservice_id=0)
    {
        $header = ['编号', '名称', '洗车类型', '创建时间', '门店', '门店id', '用户昵称', '用户id', '金额', '状态', '类型'];
        set_time_limit(0);
        $f_name = '对账单_';
        $file_Name = $f_name.$regionservice_id."_" . $start_time."_".$end_time;

        //文件存放文件夹不存在则创建
        if (!file_exists('./uploads/csv/')) {
            @mkdir("./uploads/csv/", 0777, true);
        }
        //文件路径
        $filepath = "/uploads/csv/" . $file_Name . '.csv';
        $file = fopen('.' . $filepath, "w"); //打开csv文件，如果不存在则创建
        fwrite($file, chr(0xEF) . chr(0xBB) . chr(0xBF));
        //写入头部栏目
        fputcsv($file, $header);
        foreach ($dataArr as $kk => $a) {
            //数据格式转换成 utf8
            /*$a->merchant = iconv('gb2312','utf-8',$a->merchant);
            $a->createtime = date('Y-m-d H:i:s', $a->createtime);*/
            //写入csv
            $data = [
                "id" => $a["id"],
                "name" => $a["name"],
                "card_type_name" => $a["card_type_name"],
                "createtime" => date("Y-m-d H:i:s", $a["createtime"]),
                "merchant_name" => $a["merchant_name"],
                "merchant_id" => $a["merchant_id"],
                "member_nickname" => $a["member_nickname"],
                "member_id" => $a["member_id"],
                "regionservice_commission" => $a["regionservice_commission"],
                "regionservice_status" => $a["regionservice_status"],
                "type_data" => $a["type_data"],
            ];
            fputcsv($file, $data);
        }
        //获取当前域名
        $domain = request()->domain();
        //输出下载地址
        return $domain . $filepath;
    }

    /**
     * 发起提现
     * */
    public function initiate()
    {
        $data = [
            ['type_data', 'require', '提现方式不能为空'],
            //['price', 'require', '提现金额不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        if($params["type_data"]==1 && !$this->request->param("alipayAccount")) $this->error("请输入支付宝账号");
        $user = $this->auth->getUser();
        $store = \app\common\model\Regionservice::where(["id" => $user["regionservice_id"]])->lock(true)->find();
        if ($this->request->param("start_time") && !empty($this->request->param("start_time"))) {
            //按时间提现
            $order = Order::field("sum(regionservice_commission) money")
                ->where(["regionservice_id" => $store["id"],  "regionservice_status" => '0'])
                ->whereIn("status", ['1', '3'])
                ->whereIn("type_data", ['0', '2']);
            $list = Washlog::field("sum(regionservice_commission) money")
                ->where(["regionservice_id" => $store["id"], "regionservice_status" => '0'])
                ->where("type_data <> '2'");
            if ($this->request->param("start_time") && !empty($this->request->param("start_time"))) {
                $list = $list->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
                $order = $order->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
            }
            $order = $order->buildSql();
            $list = $list->union($order, true)->select();
            $store["money"] =$list[0]["money"]+$list[1]["money"];
        }
        if (!empty($store)) {
            if (bcsub($store["money"],$params["price"])<0) $this->error("可提现余额不足");
        } else {
            $this->error("提现失败");
        }
        $params["price"]=$store["money"];
        $params["store_id"] = $store["id"];
        $params["account"] = $store["account_number"];
        $site = \think\Config::get('site');
        if ($site["minimum_money"] > $params["price"]) $this->error("最低提现" . $site["minimum_money"] . "元");
        $model = new \app\common\model\Withdrawal();
        $today_price = $model->where(["user_id" => $store["id"], "source_data" => '2'])
            ->whereTime('createtime', 'today')->sum("price");
        if ($site["highest_money"] < $today_price || $site["highest_money"] < $today_price + $params["price"]) $this->error("当日最多提现" . $site["highest_money"] . "元");
        $params["source_data"] = '2';
        $params["commission"] = floor(($params["price"] * ($site["commission"] / 100)) * 100) / 100;//手续费
        $params["actual_receipt"] = $params["price"] - $params["commission"];//实际到账
        $params["user_id"] = $this->auth->id;
        Db::startTrans();
        try {
            if($this->request->param("start_time")){
                unset($params["start_time"]);
                unset($params["end_time"]);
            }
            $model->allowField(true)->save($params);
            $store->save(["money" => $store["money"] - $params["price"]]);
            $order = Order::where(["regionservice_id" => $store["id"], "regionservice_status" => '0'])
                ->whereIn("status", ['1', '3'])
                ->whereIn("type_data", ['0', '2']);
            $list = Washlog::where(["regionservice_id" =>$store["id"], "regionservice_status" => '0'])
                ->where("type_data <> '2'");
            if ($this->request->param("start_time") && !empty($this->request->param("start_time"))) {
                $list = $list->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
                $order = $order->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")]);
            }
            $list=$list->update([
                "regionservice_status"=>'1'
            ]);
            $order=$order->update([
                "regionservice_status"=>'1'
            ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("成功");
    }
}
